package com.heima.behavior.service.impl;
import java.util.Date;

import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ApLikesBehaviorService;
import com.heima.common.exception.CustException;
import com.heima.model.behavior.dtos.LikesBehaviorDto;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApLikesBehavior;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

public class ApLikesBehaviorServiceImpl implements ApLikesBehaviorService {
    @Autowired
    MongoTemplate mongoTemplate;

    @Autowired
    ApBehaviorEntryService apBehaviorEntryService;

    @Override
    public ResponseResult like(LikesBehaviorDto dto) {
        // 1. 校验参数
        ApUser apUser = AppThreadLocalUtils.getUser();
        if (apUser == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 2. 查询行为实体
        ApBehaviorEntry apBehaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId(apUser.getId(), dto.getEquipmentId());
        if (apBehaviorEntry == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"未获取到对应的行为实体信息");
        }

        // 3. 查询是否有该行为实体的点赞记录 如果是点赞并且有记录 提示请勿重复点赞
        int operation = dto.getOperation().intValue();
        Query query = Query.query(Criteria.where("entryId").is(apBehaviorEntry.getId()).and("articleId").is(dto.getArticleId()));
        if (operation == 0) {
            ApLikesBehavior apLikesBehavior = mongoTemplate.findOne(query, ApLikesBehavior.class);

            if (apLikesBehavior != null) {
                CustException.cust(AppHttpCodeEnum.DATA_EXIST, "请不要重复点赞");
            } else {
                apLikesBehavior = new ApLikesBehavior();
                apLikesBehavior.setEntryId(apBehaviorEntry.getId());
                apLikesBehavior.setArticleId(dto.getArticleId());
                apLikesBehavior.setType((short) 0);
                apLikesBehavior.setOperation((short) 0);
                apLikesBehavior.setCreatedTime(new Date());
                mongoTemplate.save(apLikesBehavior);
            }
        } else {
            // 取消点赞  删除点赞数据
            mongoTemplate.remove(query, ApLikesBehavior.class);
        }

        return ResponseResult.okResult();
    }
}
